from PyQt5.QtCore import *
from PyQt5.QtWidgets import *
from PyQt5.QtGui import *
import os, time, sys
import cv2
from uiDef import *

class CameraWidget(QWidget):
    def __init__(self):
        super().__init__()

        #返回主界面
        self.homeBtn = QPushButton(self)
        self.homeBtn.setStyleSheet("QPushButton{border-image: url(resource/ic_home.png)}")
        self.homeBtn.setFixedSize(30, 30)
        self.headerLabel = QLabel(self)
        self.headerLabel.setText("车前路况")
        self.headerLabel.setStyleSheet("color:white")
        self.hBoxHeader = QHBoxLayout()
        self.hBoxHeader.addStretch(1)
        self.hBoxHeader.addWidget(self.headerLabel)
        self.hBoxHeader.addStretch(1)
        self.hBoxHeader.addWidget(self.homeBtn)
        
        #显示摄像头
        self.showLabel = QLabel(self)
        self.showLabel.setAlignment(Qt.AlignCenter)

        #整体布局
        self.vboxMain = QVBoxLayout()
        self.vboxMain.addLayout(self.hBoxHeader)
        self.vboxMain.addWidget(self.showLabel)
        self.setLayout(self.vboxMain)
        
        # 创建VideoCapture对象，参数为0表示使用本地摄像头
        self.timerCamera = QTimer(self)
        self.cap = cv2.VideoCapture(0)
        self.cap.set(cv2.CAP_PROP_FRAME_WIDTH, 640)
        self.cap.set(cv2.CAP_PROP_FRAME_HEIGHT, 480)
        self.timerCamera.timeout.connect(self.showCameaImg)
        self.timerCamera.start(10)
        print("start capture")

        #信号与槽
        self.homeBtn.clicked.connect(self.returnHome)
        self.homeBtn.clicked.connect(self.closeCamera)
        self.homeBtn.clicked.connect(self.close)

        self.initUI()

    # 初始化界面
    def initUI(self):
        self.resize(WIN_WIDTH, WIN_HEIGHT)
        self.setWindowTitle('车前路况')
        #self.setStyleSheet("background-color:rgb(94,38,18)")
        self.show()
        
    def paintEvent(self, event):
        palette = QPalette()
        pix = QPixmap("resource/bg/bg_camera.png").scaled(self.width(),self.height())
        palette.setBrush(QPalette.Background,QBrush(pix))
        self.setPalette(palette)   
        
    # 返回主页
    def returnHome(self):
        print("return home")
        from homeUI import mainWindow
        self.homeWindow = mainWindow()
        self.homeWindow.show()
        
    def showCameaImg(self):
        success, frame=self.cap.read()
        if success:
            show = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
            showImage = QImage(show.data, show.shape[1], show.shape[0], QImage.Format_RGB888)
            self.showLabel.setPixmap(QPixmap.fromImage(showImage))
            self.timerCamera.start(10)
        
    def closeCamera(self):
        # 释放资源
        print("capture release")
        self.cap.release()

if __name__ =='__main__':
    import sys
    app = QApplication(sys.argv)
    my_widget = CameraWidget()
    my_widget.show()
    sys.exit(app.exec())
